<?php

class ProductosController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */

	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create', 'create2','update', 'adminp', 'admine', 'adminproveedor', 'adminempleado'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete', 'create', 'create2', 'adminp', 'admine'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Productos;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Productos']))
		{
			$model->attributes=$_POST['Productos'];
				$max = Yii::app()->db->createCommand()->select('max(IDPRODUCTO) as max')->from('productos')->queryScalar();
				if($max!=null){
					$max=$max+1;
					$max="00000000$max";
					$tam = strlen($max);
					$max= substr($max, ($tam-7),$tam);
					$model->IDPRODUCTO=($max);
				}
				else{$model->IDPRODUCTO='0000000';}
				date_default_timezone_set("America/Costa_Rica"); 
				$model->FECHA=date('Y-m-d H:i:s');
				$model->TipoES=1;
				//transaccion
				$transaction=$model->dbConnection->beginTransaction();
				try{
					if($model->save()){
						//llenado de detalle
	   	     		$cont=1;
					$line=1;
					$cer=0;
					while($cont<=$_POST['cant_campos'])
					{
						if(isset($_POST['hdnCodigo_'.$cont]))
						{
							$model1 = new Detproducto;
			  	     		$model1->IDPRODUCTO=$model->IDPRODUCTO;
							$model1->IDINVENTARIO =$_POST['hdnCodigo_'.$cont];
							$model1->CANTIDAD = $_POST["hdnCant_".$cont];
							$model1->PRECIO = $_POST["hdnPrecio_".$cont];
							$model1->PRECIOV = $_POST["hdnPrecioV_".$cont];
							$model1->IDDETALLE= $line;
							$line++;

							$inventario=$this->loadModelInventario($_POST['hdnCodigo_'.$cont]);
							$inventario->CANTIDAD = ((int) $inventario->CANTIDAD + (int) $_POST["hdnCant_".$cont]);
							$inventario->PRECIO = ($inventario->PRECIO + (($_POST["hdnPrecio_".$cont]-$inventario->PRECIO)/$inventario->CANTIDAD));
							$inventario->PRECIOV = ($inventario->PRECIOV + ($_POST["hdnPrecioV_".$cont]-$inventario->PRECIOV)/$inventario->CANTIDAD);
							if(!$model1->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','Error al crear la factura');
								$line=1;
							}
							if(!$inventario->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','Error al crear la factura');
								$line=1;
							}
						}
						$cont++;
						
					}
					if($line>1)
					{
						$sql = "Insert into bitacora (IDUSUARIO, Accion, Descripcion, Fecha) Values('".Yii::app()->user->id."','1','Alta de Entrada $model->IDPRODUCTO','$model->FECHA')";
						$connection = Yii::app() -> db;
						$command = $connection -> createCommand($sql);
						$command -> execute();
						$transaction->commit();
						$this->redirect(array('view','id'=>$model->IDPRODUCTO));
						Yii::app()->user->setFlash('Error','demo'.$inventario->CANTIDAD);
					}
					else{
						Yii::app()->user->setFlash('Error','Error al crear factura'.$cont.$line);
						$transaction->rollBack();
					}
					}

				}
				catch(Exception $e){
					Yii::app()->user->setFlash('Error','Error al crear factura'.$e);
	    			//$transaction->rollBack();
				}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionCreate2()
	{
		$model=new Productos;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Productos']))
		{
			$model->attributes=$_POST['Productos'];
				$max = Yii::app()->db->createCommand()->select('max(IDPRODUCTO) as max')->from('productos')->queryScalar();
				if($max!=null){
					$max=$max+1;
					$max="00000000$max";
					$tam = strlen($max);
					$max= substr($max, ($tam-7),$tam);
					$model->IDPRODUCTO=($max);
				}
				else{$model->IDPRODUCTO='0000000';}
				date_default_timezone_set("America/Costa_Rica"); 
				$model->FECHA=date('Y-m-d H:i:s');
				$model->TipoES=0;
				//transaccion
				$transaction=$model->dbConnection->beginTransaction();
				try{
					if($model->save()){
						//llenado de detalle
	   	     		$cont=1;
					$line=1;
					$cer=0;
					while($cont<=$_POST['cant_campos'])
					{
						if(isset($_POST['hdnCodigo_'.$cont]))
						{
							$model1 = new Detproducto;
			  	     		$model1->IDPRODUCTO=$model->IDPRODUCTO;
							$model1->IDINVENTARIO =$_POST['hdnCodigo_'.$cont];
							$model1->CANTIDAD = $_POST["hdnCant_".$cont];
							$model1->PRECIO = $_POST["hdnPrecio_".$cont];
							$model1->IDDETALLE= $line;
							$line++;

							$inventario=$this->loadModelInventario($_POST['hdnCodigo_'.$cont]);
							$inventario->CANTIDAD = ((int) $inventario->CANTIDAD - (int) $_POST["hdnCant_".$cont]);
							
							if(!$model1->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','Problemas al crear el detalle de la factura');
								$line=1;
							}
							if(!$inventario->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','Problemas al restar a inventario');
								$line=1;
							}
						}
						$cont++;
						
					}
					if($line>1)
					{
						$sql = "Insert into bitacora (IDUSUARIO, Accion, Descripcion, Fecha) Values('".Yii::app()->user->id."','1','Alta de Salida de productos $model->IDPRODUCTO','$model->FECHA')";
						$connection = Yii::app() -> db;
						$command = $connection -> createCommand($sql);
						$command -> execute();
						$transaction->commit();
						$this->redirect(array('view','id'=>$model->IDPRODUCTO));
					}
					else{
						Yii::app()->user->setFlash('Error','Problemas al crear factura, intente de nuevo'.$cont.$line);
						$transaction->rollBack();
					}
					}

				}
				catch(Exception $e){
					Yii::app()->user->setFlash('Error','Error al crear factura'.$e);
	    			$transaction->rollBack();
				}
			}

		$this->render('create2',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Productos']))
		{
			$model->attributes=$_POST['Productos'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->IDPRODUCTO));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Productos');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Productos('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Productos']))
			$model->attributes=$_GET['Productos'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionAdminProveedor()
	{
		$model=new Proveedores('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Proveedores']))
			$model->attributes=$_GET['Proveedores'];

		$this->render('admin2',array(
			'model'=>$model,
		));
	}

	public function actionAdminEmpleado()
	{
		$model=new Empleados('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Empleados']))
			$model->attributes=$_GET['Empleados'];

		$this->render('admin3',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Productos the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Productos::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

//Busqueda para actualizar el inventario
	public function loadModelInventario($id)
	{
		$model=Inventario::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	/**
	 * Performs the AJAX validation.
	 * @param Productos $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='productos-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
